package com.heima.simple;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class ConusmerQuertStart {
    public static void main(String[] args) {
        //2.设置连接配置
        Properties properites=new Properties();
        //连接kafka
        properites.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.128:9092");
        //设置key和value字符串反序列化
        properites.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properites.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        //设置组id
        properites.put(ConsumerConfig.GROUP_ID_CONFIG,"group2");
        //加入设置自动提交
        properites.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
        //1.创建消费者对象
        KafkaConsumer<String,String> kafkaConsumer=new KafkaConsumer<String, String>(properites);

        //3.订阅主题
        kafkaConsumer.subscribe(Collections.singletonList("topic_kafka_end"));

        //当前线程一直处于监听状态
        while (true){
            //4.拉取消息
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println("消息的key和value的值"+consumerRecord.key()+"："+consumerRecord.value());
               /* System.out.println("接收到的消息的key:"+consumerRecord.key());
                System.out.println("接收到的消息内容:"+consumerRecord.value());
                System.out.println("消息所存在的偏移量："+consumerRecord.offset());*/
                //同步提交偏移量
                //kafkaConsumer.commitSync();

               /* //异步提交
                kafkaConsumer.commitAsync(new OffsetCommitCallback() {
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {
                        if(exception!=null){
                            System.out.println("记录错误的提交偏移量："+ offsets+",异常信息"+exception);
                        }
                    }
                });*/
            }
        }

    }
}
